<template>
  <div style="display: flex;">
    <div
      class="bg"
      style="height: 865px;position: relative;width: 1860px; margin-top: 20px;"
    >
      <div id="yunweiList">
        <div class="">
          <div
            class="d-flex"
            style="justify-content: space-between;"
          >
            <div class="title">
              <img src="../assets/icon-title.png">
              <span style="margin-left: 5px;">报表管理</span>
            </div>
            <div>
              <el-date-picker
                v-model="reportDate"
                type="date"
                placeholder="选择日期"
                size="mini"
                class="searchInput"
                style="width: 130px"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              />
              <button
                style="background-color: #1a5cd7;color:white;border: none;height: 30px;width: 80px;margin-left: 10px;"
                @click="exportExcelAll"
              >
                批量导出
              </button>
            </div>
          </div>
          <div class="d-flex jc-center body-box radio-group-container">
            <el-radio-group
              v-model="reportCata"
              @change="cataChange"
            >
              <el-radio-button label="jingchushui">
                进出水在线仪
              </el-radio-button>
              <el-radio-button label="cuge">
                预处理
              </el-radio-button>
              <el-radio-button label="aao11">
                生化池
              </el-radio-button>
              <el-radio-button label="erchengchi1">
                二沉池
              </el-radio-button>
              <el-radio-button label="qifuchi1">
                提升泵房及气浮
              </el-radio-button>
              <el-radio-button label="lvchi">
                V型滤池
              </el-radio-button>
              <el-radio-button label="xiaodu1">
                消毒池及再生泵房
              </el-radio-button>
              <el-radio-button label="nongsuo">
                浓缩池
              </el-radio-button>
              <el-radio-button label="zhuningji1">
                加药间
              </el-radio-button>
              <el-radio-button label="tuoshuiji1">
                脱水机房
              </el-radio-button>
              <el-radio-button label="chuchou">
                除臭系统
              </el-radio-button>
            </el-radio-group>
          </div>
          <div class="d-flex jc-center body-box">
            <el-menu
              :default-active="activeTable"
              class="el-menu-demo"
              mode="horizontal"
              background-color="#0B131B"
              text-color="#8CB1D6"
              active-text-color="#409eff"
              @select="handleSelect"
            >
              <el-menu-item
                v-show="reportCata=='jingchushui'"
                index="jingchushui"
              >
                进出水仪表间
              </el-menu-item>
              <el-menu-item
                v-show="reportCata=='cuge'"
                index="cuge"
              >
                粗格栅及进水泵房
              </el-menu-item>

              <el-menu-item
                v-show="reportCata=='cuge'"
                index="xige1"
              >
                细格删及曝气沉砂池
              </el-menu-item>

              <el-menu-item
                v-show="reportCata=='aao11'"
                index="aao11"
              >
                东1#多模式AAO反应池
              </el-menu-item>
              <el-menu-item
                v-show="reportCata=='aao11'"
                index="aao21"
              >
                东2#多模式AAO反应池
              </el-menu-item>
              <el-menu-item
                v-show="reportCata=='aao11'"
                index="aao31"
              >
                西1#多模式AAO反应池
              </el-menu-item>
              <el-menu-item
                v-show="reportCata=='aao11'"
                index="aao41"
              >
                西2#多模式AAO反应池
              </el-menu-item>

              <el-menu-item
                v-show="reportCata=='aao11'"
                index="kongqi1"
              >
                空气悬浮离心鼓风机
              </el-menu-item>
              <el-menu-item
                v-show="reportCata=='erchengchi1'"
                index="erchengchi1"
              >
                东组二沉池
              </el-menu-item>
              <el-menu-item
                v-show="reportCata=='erchengchi1'"
                index="erchengchi2"
              >
                西组二沉池
              </el-menu-item>

              <el-menu-item
                v-show="reportCata=='qifuchi1'"
                index="qifuchi1"
              >
                高效气浮池
              </el-menu-item>
              <el-menu-item
                v-show="reportCata=='zhuningji1'"
                index="zhuningji1"
              >
                混助凝剂投加
              </el-menu-item>
              <el-menu-item
                v-show="reportCata=='zhuningji1'"
                index="tanyuan"
              >
                碳源投加
              </el-menu-item>
              <el-menu-item
                v-show="reportCata=='lvchi'"
                index="lvchi"
              >
                V型滤池
              </el-menu-item>
              <el-menu-item
                v-show="reportCata=='xiaodu1'"
                index="xiaodu1"
              >
                接触消毒池及尾水泵房
              </el-menu-item>
              <el-menu-item
                v-show="reportCata=='tuoshuiji1'"
                index="tuoshuiji1"
              >
                1#离心脱水机
              </el-menu-item>
              <el-menu-item
                v-show="reportCata=='tuoshuiji1'"
                index="tuoshuiji2"
              >
                2#离心脱水机
              </el-menu-item>
              <el-menu-item
                v-show="reportCata=='tuoshuiji1'"
                index="tuoshuiji3"
              >
                3#离心脱水机
              </el-menu-item>
              <el-menu-item
                v-show="reportCata=='nongsuo'"
                index="nongsuo"
              >
                浓缩池
              </el-menu-item>
              <el-menu-item
                v-show="reportCata=='tuoshuiji1'"
                index="yunzhi"
              >
                匀质池
              </el-menu-item>
              <el-menu-item
                v-show="reportCata=='tuoshuiji1'"
                index="peiyao"
              >
                料仓、配药
              </el-menu-item>
              <el-menu-item
                v-show="reportCata=='chuchou'"
                index="chuchou"
              >
                除臭-生化区
              </el-menu-item>
              <el-menu-item
                v-show="reportCata=='chuchou'"
                index="chuchou1"
              >
                除臭-预处理区及污泥处理区
              </el-menu-item>
            </el-menu>
          </div>
          <div style="padding: 30px 180px;">
            <div
              v-for="table in allTables"
              v-show="table.reportCode==activeTable"
              :id="'tableAll'+table.reportCode"
              :key="table.id"
            >
              <el-table
                :id="'print-table-'+table.reportCode"
                ref="multipleTable"
                :data="tableData"
                size="mini"
                highlight-current-row
                border
                class="el-tb-edit mgt20"
                tooltip-effect="dark"
                :span-method="arraySpanMethod(tableData,fieldsMap,table.reportCode)"
                :row-class-name="tableRowClassNameBase"
                height="600"
              >
                <el-table-column
                  align="center"
                  :label="table.reportName.split('.')[1]"
                >
                  <el-table-column :label="'日期：'+ reportDate">
                    <el-table-column
                      align="center"
                      label="班次"
                      width="55"
                      prop="belong_hour"
                    >
                      <template slot-scope="scope">
                        <span>{{ formatBelongHour(scope.row.belong_hour) }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      align="center"
                      label="时间"
                      width="55"
                      prop="belong_hour"
                    />
                    <template
                      v-for="(columnData,index) in buildHeaderTree(table.reportTableFieldsList,fieldsMap)"
                    >
                      <table-column
                        :key="index"
                        :head-column="columnData"
                      />
                    </template>
                  </el-table-column>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
	import tableColumn from './component/tableColumn.vue'
	export default {
		components: {
			tableColumn
		},
		data() {
			return {

				reportDate: "",
				reportCata: "jingchushui",
				url: {
					allTables: '/api/report/data/allTables',
					tableData: '/api/report/data/list',
					fieldsMap: '/api/report/reportFields/allMap',
					
					exportOne: '/api/report/data/exportOne',
				},
				fieldsMap: {},
				loading: false,
				tableData: [],
				allTables: [],
				allTablesNames: {},
				activeTable: 'jingchushui',
			}
		},
		watch: {
			activeTable() {
				console.log(this.activeTable, "this.activeTable")
				this.loading = false
				// this.getRunTime()
				this.getTableData(this.activeTable)
			},

			reportDate() {
				this.loading = false
				// this.getRunTime()
				this.getTableData(this.activeTable)
			}

		},
		mounted() {
			this.getFieldsMaps()
			this.reportDate = this.$moment().subtract(1, 'days').format('YYYY-MM-DD')
			this.getAllTables()
		},
		methods: {
			handleSelect(key) {
				this.activeTable = key
			},
			cataChange: function() {
				this.activeTable = this.reportCata
			},
			// 构建表头树
			buildHeaderTree(columns, labels) {
				const headerMap = {}

				columns.forEach(column => {
					const fieldCode = column.fieldCode
					const countType = column.countType
					const labelStr = labels[fieldCode].fieldName
					const labelParts = labelStr.split('｜')

					let currentLevel = headerMap

					// 按照每一级表头创建树形结构
					labelParts.forEach((label, index) => {
						if (!currentLevel[label]) {
							currentLevel[label] = {
								label: label,
								children: {}
							}
						}
						// 最后一层绑定prop
						if (index === labelParts.length - 1) {
							currentLevel[label].prop = fieldCode
							currentLevel[label].countType = countType
						}
						currentLevel = currentLevel[label].children
					})
				})
				// 转换为数组格式的树结构
				var headerTree = this.mapToTree(headerMap)
				// console.log(headerTree, 'headerTree')
				return headerTree
			},
			// 将对象映射为树形结构数组
			mapToTree(map) {
				return Object.keys(map).map(key => {
					const node = {
						label: key,
						children: map[key].children ? this.mapToTree(map[key].children) : null,
						prop: map[key].prop || null,
						countType: map[key].countType,
						width: 80
					}

					return node
				})
			},
			formatBelongHour(belongHour) {
				if (belongHour === 'total') {
					return '累计/平均'
				} else if (belongHour === 'max') {
					return '最大值'
				} else if (belongHour === 'min') {
					return '最小值'
				} else if (belongHour >= '08:00' && belongHour <= '18:00') {
					return '日班'
				} else {
					return '夜班'
				}
			},
			arraySpanMethod(tableData, fieldsMap, reportCode) {
				return ({
					row,
					rowIndex,
					columnIndex
				}) => {
					// 累计/平均 合并
					if (rowIndex === tableData.length - 1) {
						if (columnIndex === 0) {
							return [1, 2] // 合并第一列和第二列（rowspan 为 1，colspan 为 2）
						} else if (columnIndex === 1) {
							return [0, 0] // 隐藏第二列
						}
					}
					if (reportCode === 'jingchushui') {
						if (rowIndex === tableData.length - 2 || rowIndex === tableData.length - 3) {
							if (columnIndex === 0) {
								return [1, 2] // 合并第一列和第二列（rowspan 为 1，colspan 为 2）
							} else if (columnIndex === 1) {
								return [0, 0] // 隐藏第二列
							}
						}
						if (rowIndex === tableData.length - 1) {
							if (columnIndex === 10) {
								return [1, 2] // 合并第一列和第二列（rowspan 为 1，colspan 为 2）
							} else if (columnIndex === 11) {
								return [0, 0] // 隐藏第二列
							}
						}
					}
					// 合并第一列（belong_hour列）
					if (columnIndex === 0) {
						const prevRow = tableData[rowIndex - 1]
						if (prevRow && this.formatBelongHour(prevRow.belong_hour) === this.formatBelongHour(row
								.belong_hour)) {
							return [0, 0]
						}
						let rowspan = 1
						for (let i = rowIndex + 1; i < tableData.length; i++) {
							if (this.formatBelongHour(tableData[i].belong_hour) === this.formatBelongHour(row
									.belong_hour)) {
								rowspan++
							} else {
								break
							}
						}
						return [rowspan, 1]
					}
				}
			},
			tableRowClassNameBase() {
				// 偶数行使用 high-row 类，奇数行使用 default-row 类
				return 'default-row-base'
			},
			getFieldsMaps() {
				var _this = this
				this.$ajax({
					method: 'get',
					url: this.url.fieldsMap
				}).then(function(resultData) {
					var fieldsMap = resultData.data.data.map
					_this.fieldsMap = fieldsMap
					// console.log(fieldsMap, 'fieldsMap')
				})
			},
			getAllTables() {
				var _this = this
				this.$ajax({
					method: 'get',
					url: this.url.allTables,
					params: {
						tableType: '1'
					}
				}).then(function(resultData) {
					var allTables = resultData.data.data.list
					_this.allTables = allTables
					for (let i = 0; i < allTables.length; i++) {
						// _this.getTableData(allTables[i]['reportCode'])
						_this.allTablesNames[allTables[i]['reportCode']] = allTables[i]['reportName']
					}
					_this.getTableData(_this.activeTable)

				})
			},
			getTableData(reportCode) {
				var _this = this
				this.$ajax({
					method: 'get',
					url: this.url.tableData,
					params: {
						reportCode,
						reportDate: this.reportDate
					}
				}).then(function(resultData) {
					const tableDataOne = resultData.data.data.list
					// _this.tableData[reportCode] = tableDataOne
					_this.tableData = tableDataOne
					_this.loading = false
					// console.log(_this.tableData)
					// _this.tableData = JSON.parse(JSON.stringify(_this.tableData))
				})
			},
			exportExcel(reportCode) {
				var _this = this
				this.$ajax({
					method: 'get',
					url: this.url.exportOne,
					responseType: 'blob',
					params: {
						reportCode,
						reportDate: this.reportDate
					}
				}).then(function(res) {
					var blob = new Blob([res])
					console.log(blob.size)
					if (blob.size < 1) {
						return
					}
					const url = URL.createObjectURL(blob)
					// 模拟点击下载按钮下载文件
					const link = document.createElement('a')
					link.style.display = 'none'
					link.href = url
					link.download = _this.reportDate + '_' + _this.allTablesNames[reportCode] + '.xlsx'
					document.body.appendChild(link)
					link.click()
					// 释放 URL 对象
					window.URL.revokeObjectURL(url)
				})
			},
			exportExcelOne() {
				this.exportExcel(this.activeTable)
				// this.$ajax({
				//   method: 'get',
				//   url: this.url.exportOne,
				//   params: {
				//     reportCode: this.activeTable,
				//     reportDate: this.reportDate
				//   }
				// }).then(function(resultData) {

				// })
			},
			exportExcelAll() {
				const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) // 延时函数
				const exportWithDelay = async () => {
					for (let i = 0; i < this.allTables.length; i++) {
						const reportCode = this.allTables[i]['reportCode']
						try {
							this.exportExcel(reportCode) // 调用导出方法
							console.log(`文件 ${reportCode} 导出成功`)
						} catch (error) {
							console.error(`文件 ${reportCode} 导出失败:`, error)
						}
						await delay(200) // 每次导出后延时 500 毫秒
					}

					this.$message.success('所有文件已导出完成！')
				}
				exportWithDelay() // 调用异步函数
			}

		}
	}
</script>
<style>
	.high-row {
		height: 60px !important;
	}

	.default-row {
		height: 15px !important;
	}

	.default-row-base {
		height: 35px !important;
	}
</style>
<style lang="scss" scoped>
	$box-height3: 840px;
	$box-width3: 100%;

	#yunweiList {
		padding: 16px;
		padding-top: 20px;
		height: $box-height3;
		width: $box-width3;
		border-radius: 5px;

		.bg-color-black3 {
			height: $box-height3 - 30px;
			border-radius: 10px;
		}

		.text {
			color: #c3cbde;
		}

		// .body-box {
		// 	border-radius: 10px;
		// 	overflow: hidden;

		// }
		// .dv-scr-board {
		// 	width: 100%;
		// 	height: 740px;
		// }


	}
</style>
<style scoped>
	/* /deep/.searchInput input{height: 30px;} */
	/* 	/deep/.el-tabs__item {
		color: #6e8194 !important;
		border: 1px solid #535353 !important;
	}

	/deep/.el-tabs__item:hover {
		color: #409EFF !important;
		cursor: pointer;
	}

	/deep/.el-tabs__item.is-active {
		color: #409EFF !important;
	}

	/deep/.el-tabs__nav {
		border: 1px solid #535353 !important;
	}

	/deep/.el-tabs__header {
		border-bottom: none !important;
	}
 */
	/deep/.el-menu.el-menu--horizontal {
		border-bottom: none !important;

	}

	/deep/.el-menu-item {
		height: 45px;
		padding: 0 5px;
		margin: 10px;
		font-size: 12px;
		background-color: transparent !important;
	}

	/deep/.el-menu:last-child {
		margin-right: 0px !important;
	}

	/deep/.el-table {
		background-color: transparent !important;
		border: 1px solid #000000 !important;
	}

	/deep/.el-table--border::after,
	.el-table--group::after,
	.el-table::before {
		background-color: transparent !important;
	}

	/deep/.el-table thead.is-group th.el-table__cell {
		background: #061b30 !important;
		border: 1px solid #000000 !important;
	}

	/deep/.el-table td.el-table__cell {
		background: #0b1325 !important;
		border: 1px solid #000000 !important;
		color: #c3cbde !important;
	}

	/deep/.radio-group-container .el-radio-button {
		margin-right: 10px;
		/* 设置右侧间距 */
		/* border-radius: 10px; */
	}

	/deep/.radio-group-container .el-radio-button__inner {
		border-radius: 5px;
		background-color: transparent;
		/* 设置背景色为透明 */
		color: #8CB1D6;
		/* 设置文字颜色为蓝色 */
		/* border-color: #1548a1; */
		/* 设置边框颜色为蓝色 */
		border: none;
		border: 2px solid #1a5cd7;
	}

	/deep/ .el-radio-button.is-active .el-radio-button__inner {
		background-color: #1a5cd7;
		/* 选中时背景色仍为透明 */
		color: #ffffff;
		/* 选中时文字颜色为蓝色 */
		border: 2px solid #1a5cd7;
		/* 选中时边框颜色为蓝色 */
	}

	/deep/.el-radio-button__orig-radio:checked+.el-radio-button__inner {
		box-shadow: none
	}

	/deep/ .el-table .cell {
		white-space: pre-wrap;
		word-wrap: break-word;
		line-height: 1.5;
		/* font-size: 11px; */
		padding: 0;

	}

	/deep/ .el-table th {
		height: 35px;

	}

	/deep/ .el-table tr:first-child th:first-child {
		height: 40px;
		/* 自定义表头高度 */
		font-size: 20px;

	}

	/deep/.el-input__inner {
		background-color: transparent !important;
		border: 1px solid #6989a7;
		color: #84a9ce
	}

	/deep/.el-input__prefix,
	.el-input__suffix {
		color: #84a9ce
	}

	/* 自定义 el-table 滚动条样式 */
	/deep/.el-table__body-wrapper::-webkit-scrollbar {
		width: 4px;
		/* 设置滚动条宽度 */
		height: 4px;
		/* 设置横向滚动条宽度 */
	}

	/deep/.el-table__body-wrapper::-webkit-scrollbar-thumb {
		background: rgba(0, 0, 0, 0.4);
		/* 滚动条滑块颜色 */
		border-radius: 2px;
		/* 圆角 */
	}

	/deep/.el-table__body-wrapper::-webkit-scrollbar-thumb:hover {
		background: rgba(0, 0, 0, 0.6);
		/* 滑块悬停时颜色 */
	}

	/deep/.el-table__body-wrapper::-webkit-scrollbar-track {
		background: rgba(0, 0, 0, 0.1);
		/* 滚动条轨道颜色 */
		border-radius: 2px;
		/* 圆角 */
	}
</style>
